package com.gilight.base.util;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

public class ExportExcel {
    public static byte[] getExportTemplate(String filePath) {
        InputStream is = null;
        byte[] bytes = null;
        try {
            is = ExportExcel.class.getResourceAsStream(filePath);
            bytes = new byte[is.available()];
            is.read(bytes);
            is.close();
        } catch (Exception e) {
            System.out.println("文件读取错误!");
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bytes;
    }

//    public static ResponseEntity<byte[]> getExportTemplate(String filePath, String fileNewName) throws UnsupportedEncodingException {
//        byte[] buffer = getExportTemplate(filePath);
//        return sendToWeb(buffer, fileNewName);
//    }

    public static ResponseEntity<byte[]> sendToWeb(byte[] bytes, String fileNewName) throws UnsupportedEncodingException {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attchement;filename="
                + URLEncoder.encode(fileNewName, "UTF-8"));
//        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        HttpStatus statusCode = HttpStatus.OK;
        return new ResponseEntity<>(bytes, headers, statusCode);
    }

    public static <T> byte[] export(List<T> data, String[] headerTitle, String[] columnName) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();


        // 设置字体样式
        XSSFCellStyle redStyle  = workbook.createCellStyle();
        XSSFFont redFont = workbook.createFont();
        redFont.setColor(Font.COLOR_RED);
        redStyle.setFont(redFont);

        int rowNum = 0;
        XSSFRow firstRow = sheet.createRow(rowNum);
        int length = headerTitle.length;
        for (int i = 0; i < length; i++) {
            String title = headerTitle[i];
            XSSFCell cell = firstRow.createCell(i);
            // 判断如果表头里面带*标记为红色字体
            if (StringUtils.isNotBlank(title) && title.contains("*")){
                cell.setCellStyle(redStyle);
            }
            cell.setCellValue(title);
        }
        rowNum++;
        if (CollectionUtils.isNotEmpty(data)) {
            for (T item : data) {
                XSSFRow row = sheet.createRow(rowNum);
                for (int i = 0; i < length; i++) {
                    try {
                        if(item instanceof Map){
                            Map map=(Map)item;
                            XSSFCell cell = row.createCell(i);
                            cell.setCellValue(map.get(columnName[i])!=null?map.get(columnName[i]).toString():"");
                        }else {
                            Field field = item.getClass().getDeclaredField(columnName[i]);
                            field.setAccessible(true);
                            Object o = field.get(item);
                            String value = o == null ? "" : o.toString();
                            XSSFCell cell = row.createCell(i);
                            cell.setCellValue(value);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                rowNum++;
            }
        }
        byte[] bytes = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            workbook.write(byteArrayOutputStream);
            bytes = byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (byteArrayOutputStream != null) {
                    byteArrayOutputStream.close();
                }
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bytes;
    }

    public static <T> byte[] exportNoBean(List<Map<String,Object>> data, String[] headerTitle, String[] columnName) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();
        int rowNum = 0;
        XSSFRow firstRow = sheet.createRow(rowNum);
        int length = headerTitle.length;
        for (int i = 0; i < length; i++) {
            String title = headerTitle[i];
            XSSFCell cell = firstRow.createCell(i);
            cell.setCellValue(title);
        }
        rowNum++;
        if (CollectionUtils.isNotEmpty(data)) {
            for (Map<String,Object> item : data) {
                XSSFRow row = sheet.createRow(rowNum);
                for (int i = 0; i < length; i++) {
                    try {
                        Object o = item.get(columnName[i]);
                        String value = o == null ? "" : o.toString();
                        XSSFCell cell = row.createCell(i);
                        cell.setCellValue(value);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                rowNum++;
            }
        }
        byte[] bytes = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            workbook.write(byteArrayOutputStream);
            bytes = byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (byteArrayOutputStream != null) {
                    byteArrayOutputStream.close();
                }
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bytes;
    }
}
